import 'dart:convert';
import 'dart:io';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:common_utils/common_utils.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:image_picker/image_picker.dart';
import 'package:provider/provider.dart';
import 'package:taonile/config/config.dart';
import 'package:taonile/utils/double_utils.dart';

import '../entity/user_info_entity.dart';
import '../http/api.dart';
import '../provider/userinfo_provider.dart';
import '../routers/routers.dart';
import '../utils/oss_upload_util.dart';
import '../utils/singleton_manager.dart';
import '../views/dialog_manager.dart';

///
/// 我的股票
///
class MineStock extends StatefulWidget {
  const MineStock({Key? key}) : super(key: key);

  @override
  State<MineStock> createState() => _MineStockState();
}

class _MineStockState extends State<MineStock> {
  String imgUrl = '';
  String name = '';
  String price = '0';
  String amountValue = '0';
  String amountValue2 = '0';

  @override
  void initState() {
    super.initState();
    getDatas();
  }

  getDatas() async {
    dynamic result = await Api.stockInfo();
    var jsonResult = jsonDecode(jsonEncode(result));
    if (jsonResult['code'] == 1) {
      setState(() {
        imgUrl = jsonResult['data']['image'];
        name = jsonResult['data']['name'];
        price = jsonResult['data']['current_price'];
      });
    }
  }

  //计算股票总价值
  getStockAmount(UserInfoEntity entity, String price) {
    double numD = double.parse(entity.data.stockNum);
    double numD2 = double.parse(entity.data.floatingStock);
    double priceD = double.parse(price);

    amountValue = '≈￥${DoubleUtils.formartNum(numD * priceD, 2)}';
    amountValue2 = '≈￥${DoubleUtils.formartNum(numD2 * priceD, 2)}';
  }

  chooseImage() async {
    final ImagePicker _picker = ImagePicker();
    final XFile? image = await _picker.pickImage(source: ImageSource.gallery);
    String? imgPah = image?.path;
    if (imgPah != null) {
      LogUtil.v(imgPah, tag: '选择的图片路径=');
      EasyLoading.show(status: 'loading...');
      String result = await UploadOss.upload(File(imgPah), fileType: UploadOss.getFileType(imgPah));
      LogUtil.v(result);
      EasyLoading.dismiss();
      return result;
    }
    return '';
  }

  upUserInfo(Function onSucces, String certificates) async {
    dynamic result = await Api.upUserinfo({'certificates': certificates});
    var jsonResult = jsonDecode(jsonEncode(result));
    if (jsonResult['code'] == 1) {
      dynamic users = await Api.getUserinfo();
      Map<String, dynamic> resultUsers = Map.from(users);
      UserInfoEntity infoEntity = UserInfoEntity.fromJson(resultUsers);
      onSucces(infoEntity);
    }
  }

  delCertificates(Function onSucces) async {
    dynamic result = await Api.delCertificates();
    var jsonResult = jsonDecode(jsonEncode(result));
    if (jsonResult['code'] == 1) {
      dynamic users = await Api.getUserinfo();
      Map<String, dynamic> resultUsers = Map.from(users);
      UserInfoEntity infoEntity = UserInfoEntity.fromJson(resultUsers);
      onSucces(infoEntity);
    }
  }

  @override
  Widget build(BuildContext context) {
    UserInfoEntity infoEntity = Provider.of<UserInfoProvider>(context).userInfo;
    getStockAmount(infoEntity, price);

    return Scaffold(
        backgroundColor: Config.colorBg2,
        appBar: AppBar(
          title: Text('我的股票'),
          centerTitle: true,
          // actions: <Widget>[
          //   TextButton(
          //     child: Text(
          //       '兑换明细',
          //       style: TextStyle(color: Config.colorText1, fontSize: 26.w),
          //     ),
          //     onPressed: () {
          //       Routes.navigateTo(context, Routes.assetGeneralDetail, params: {
          //         'pageTitle': '股票明细',
          //         'assetType': 'stock_num',
          //         'amount': infoEntity.data.stockNum
          //       });
          //     },
          //   ),
          // ],
        ),
        body: SizedBox(
          width: double.infinity,
          height: double.infinity,
          child: Column(
            children: [
              Container(
                width: double.infinity,
                height: 270.w,
                padding: EdgeInsets.symmetric(vertical: 25.w, horizontal: 25.w),
                margin: EdgeInsets.fromLTRB(30.w, 30.w, 30.w, 0),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(12.w),
                ),
                child: Column(
                  children: [
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Container(
                          margin: EdgeInsets.only(left: 0.w, right: 20.w),
                          child: ClipRRect(
                            borderRadius: BorderRadius.circular(22.w),
                            child: CachedNetworkImage(
                              imageUrl: imgUrl,
                              fit: BoxFit.fill,
                              width: 44.w,
                              height: 44.w,
                              placeholder: (context, str) {
                                return Image.asset(
                                  'assets/images/bg_default_400.png',
                                  width: 44.w,
                                  height: 44.w,
                                  fit: BoxFit.fill,
                                );
                              },
                              errorWidget: (context, url, error) {
                                return Image.asset(
                                  'assets/images/bg_default_400.png',
                                  width: 44.w,
                                  height: 44.w,
                                  fit: BoxFit.fill,
                                );
                              },
                            ),
                          ),
                        ),
                        Text(
                          name,
                          style: TextStyle(fontSize: 28.sp, color: Config.colorText1),
                        ),
                      ],
                    ),
                    Divider(
                      height: 50.w,
                      thickness: 2.w,
                      color: Config.colorDivider,
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      children: [
                        InkWell(
                          onTap: () {
                            Routes.navigateTo(context, Routes.assetYuanshiguDetail, params: {
                              'pageTitle': '原始股',
                              'assetType': 'stock_num',
                              'amount': infoEntity.data.stockNum,
                              'amount2': amountValue,
                            });
                          },
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              Text(
                                '原始股',
                                style: TextStyle(fontSize: 27.sp, color: Config.colorText1),
                              ),
                              Padding(
                                padding: EdgeInsets.only(top: 15.w),
                              ),
                              Text(
                                infoEntity.data.stockNum,
                                style: TextStyle(fontSize: 23.sp, color: Config.colorText1),
                              ),
                              Padding(
                                padding: EdgeInsets.only(top: 5.w),
                              ),
                              Text(
                                amountValue,
                                style: TextStyle(fontSize: 20.sp, color: Config.colorText1),
                              ),
                            ],
                          ),
                        ),
                        Container(
                          width: 2.w,
                          height: 120.w,
                          decoration: const BoxDecoration(
                            color: Config.colorDivider,
                          ),
                        ),
                        InkWell(
                          onTap: () {
                            Routes.navigateTo(context, Routes.assetYuanshiguDetail, params: {
                              'pageTitle': '流通股',
                              'assetType': 'floating_stock',
                              'amount': infoEntity.data.floatingStock,
                              'amount2': amountValue2,
                            });
                          },
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              Text(
                                '流通股',
                                style: TextStyle(fontSize: 27.sp, color: Config.colorText1),
                              ),
                              Padding(
                                padding: EdgeInsets.only(top: 15.w),
                              ),
                              Text(
                                infoEntity.data.floatingStock,
                                style: TextStyle(fontSize: 23.sp, color: Config.colorText1),
                              ),
                              Padding(
                                padding: EdgeInsets.only(top: 5.w),
                              ),
                              Text(
                                amountValue2,
                                style: TextStyle(fontSize: 20.sp, color: Config.colorText1),
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                    // Positioned(
                    //   bottom: 0,
                    //   right: 0.w,
                    //   child: Container(
                    //     width: 200.w,
                    //     height: 50.w,
                    //     child: ElevatedButton(
                    //       clipBehavior: Clip.antiAlias,
                    //       onPressed: () async {
                    //         Routes.navigateTo(context, Routes.mineStockExchange);
                    //       },
                    //       style: ElevatedButton.styleFrom(shape: const StadiumBorder()),
                    //       child: Text('前往兑换', style: TextStyle(fontSize: 24.sp)),
                    //     ),
                    //   ),
                    // ),
                  ],
                ),
              ),
              Container(
                width: double.infinity,
                height: 450.w,
                padding: EdgeInsets.symmetric(vertical: 25.w, horizontal: 25.w),
                margin: EdgeInsets.fromLTRB(30.w, 30.w, 30.w, 0),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(12.w),
                ),
                child: Column(
                  children: [
                    Container(
                      height: 40.w,
                      margin: EdgeInsets.only(top: 0.w),
                      width: double.infinity,
                      padding: EdgeInsets.symmetric(horizontal: 0.w),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          Text(
                            '我的股权证',
                            style: TextStyle(fontSize: 27.sp, color: Config.colorText1),
                          ),
                        ],
                      ),
                    ),
                    Divider(
                      height: 50.w,
                      thickness: 2.w,
                      color: Config.colorDivider,
                    ),
                    Container(
                      width: 400.w,
                      height: 300.w,
                      alignment: Alignment.center,
                      // decoration: BoxDecoration(color: Config.colorDivider),
                      child: Stack(
                        children: [
                          Visibility(
                            visible: infoEntity.data.stockCertificates.isEmpty,
                            child: InkWell(
                              onTap: () async {
                                String str = await chooseImage();
                                if (str.isNotEmpty) {
                                  upUserInfo((UserInfoEntity infoEntity) {
                                    Provider.of<UserInfoProvider>(context, listen: false)
                                        .changeUserinfo(infoEntity);
                                    EasyLoading.showToast('提交成功');
                                  }, str);
                                }
                              },
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  Text(
                                    '暂未上传',
                                    style: TextStyle(fontSize: 27.sp, color: Config.colorText1),
                                  ),
                                  Text(
                                    '请上传你的股权证',
                                    style: TextStyle(
                                        fontSize: 24.sp, height: 2, color: Config.colorText3),
                                  ),
                                  Padding(
                                    padding: EdgeInsets.only(top: 10.w),
                                  ),
                                  Icon(
                                    Icons.add_box_outlined,
                                    size: 50.w,
                                    color: Config.colorText3,
                                  ),
                                ],
                              ),
                            ),
                          ),
                          Visibility(
                            visible: infoEntity.data.stockCertificates.isNotEmpty,
                            child: Stack(
                              children: [
                                ClipRRect(
                                  borderRadius: BorderRadius.circular(5),
                                  child: CachedNetworkImage(
                                    imageUrl: infoEntity.data.stockCertificates,
                                    fit: BoxFit.fitHeight,
                                    width: double.infinity,
                                    height: double.infinity,
                                    errorWidget: (context, url, error) {
                                      return Image.asset(
                                        'assets/images/bg_default_400.png',
                                        width: double.infinity,
                                        height: double.infinity,
                                        fit: BoxFit.fitHeight,
                                      );
                                    },
                                  ),
                                ),
                                Positioned(
                                  right: 0,
                                  child: InkWell(
                                    onTap: () {
                                      DialogManager.showDefaultDialog(context, "确认删除凭证吗？",
                                          () async {
                                        delCertificates((UserInfoEntity infoEntity) {
                                          Provider.of<UserInfoProvider>(context, listen: false)
                                              .changeUserinfo(infoEntity);
                                          EasyLoading.showToast('删除成功');
                                        });
                                      });
                                    },
                                    child: Container(
                                      width: 55.w,
                                      height: 55.w,
                                      alignment: Alignment.center,
                                      decoration: BoxDecoration(
                                        color: Config.colorBg2,
                                        borderRadius: BorderRadius.circular(25.w),
                                      ),
                                      child: Icon(
                                        Icons.delete_forever,
                                        size: 40.w,
                                      ),
                                    ),
                                  ),
                                ),
                                Positioned(
                                  left: 165.w,
                                  top: 115.w,
                                  child: InkWell(
                                    onTap: () {
                                      List newlist = [infoEntity.data.stockCertificates];
                                      SingletonManager.instance.galleryItems = newlist;
                                      Routes.navigateTo(context, Routes.photoPreview,
                                          transition: TransitionType.fadeIn,
                                          params: {'defaultImage': '0'});
                                    },
                                    child: Container(
                                      width: 60.w,
                                      height: 60.w,
                                      alignment: Alignment.center,
                                      decoration: BoxDecoration(
                                        color: const Color(0xAAFFFFFF),
                                        borderRadius: BorderRadius.circular(30.w),
                                      ),
                                      child: Icon(
                                        Icons.search,
                                        size: 40.w,
                                      ),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    )
                  ],
                ),
              ),
            ],
          ),
        ));
  }
}
